package com.xiong.word;

import com.xiong.word.ext.XWPFParagraphCallback;
import com.xiong.word.model.TableModel;
import com.xiong.word.model.XWPFParagraphModel;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class WordEngine {

    private String path;

    private XWPFDocument document;

    private FileInputStream fileInputStream;

    public WordEngine(String path){
        this.path=path;
        this.createXWPFDocument(this.path);
    }

    /**
     * 处理表格
     * @param tableIndex
     * @return
     */
    public TableModel dealTable(int tableIndex){
        XWPFTable table = document.getTables().get(tableIndex);
        TableModel tableModel=new TableModel(table,this);
        return tableModel;
    }

    /**
     * 处理段落
     * @param ext
     */
    public WordEngine dealXWPFParagraph(XWPFParagraphCallback ext){
        List<XWPFParagraph> paragraphs = this.document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            XWPFParagraphModel model=new XWPFParagraphModel(paragraph);
            ext.dealXWPFParagraph(model);
        }
        return this;
    }

    public void outPath(String path){
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(path);
            this.document.write(output);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(output!=null){
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void createXWPFDocument(String path){
        try {
            this.fileInputStream=new FileInputStream(path);
            this.document=new XWPFDocument(this.fileInputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
